﻿using HuRongClub.DBUtility;
using MintCyclingData;
using MintCyclingService.alipay;
using MintCyclingService.Common;
using MintCyclingService.LogServer;
using MintCyclingService.UserAccount;
using MintCyclingService.UserRecharge;
using MintCyclingService.Utils;
using System;
using System.Data;
using System.Linq;
using System.Text;
using Utility.Common;
using Utility.LogHelper;
using WxPayAPI;

namespace MintCyclingService.WeixinApliay
{
    /// <summary>
    /// 微信支付服务类
    /// </summary>
    public class WeixinAlipayTradeService : IWeixinAlipayTradeService
    {
        //获取配置文件中的值  
      
        private static string YjAmoiunt = System.Web.Configuration.WebConfigurationManager.AppSettings["YjAmount"];       //押金
        //private static string Sslcert_path = System.Web.Configuration.WebConfigurationManager.AppSettings["Sslcert_path"];       //证书路径
        //private static string Sslcert_password = System.Web.Configuration.WebConfigurationManager.AppSettings["Sslcert_password"];       //证书密码
        private static string String_IP = System.Web.Configuration.WebConfigurationManager.AppSettings["String_IP"];       //ip
        private static string W_notify_url = System.Web.Configuration.WebConfigurationManager.AppSettings["W_notify_url"];       //付异步通知
        //private static string notify_url = System.Web.Configuration.WebConfigurationManager.AppSettings["notify_url"];      //获取服务器异步通知页面路径



        //接口实例化对象
        private IUserAccountService _UserAccountService = new UserAccountService();
        private IUserRechargeRecordService _UserRechargeService = new UserRechargeRecordService();
        private ILogService LogService = new LogService();

        #region 统一下单处理相关接口

        /// <summary>
        /// 商户系统先调用该接口在微信支付服务后台生成预支付交易单，返回正确的预支付交易回话标识后再在APP里面调起支付
        /// 商户发起生成预付单请求
        /// URL地址：https://api.mch.weixin.qq.com/pay/unifiedorder
        /// </summary>
        /// <returns></returns>
        public ResultModel GetWeiXinTradeAppPay(WeixinAlipayTradeModel para)
        {
            var result = new ResultModel();
            string Return_code = string.Empty;
            string err_code = string.Empty;
            string strCode = string.Empty;
            string typeName = "WeixinRechargeLog";
            string OrderNumber = string.Empty;

            //生成唯一的订单号
            if (para.TypeName == 1) //押金充值
            {
                OrderNumber = "YJ" + OrderHelper.GenerateOrderNumber();
            }
            else //余额充值
            {
                OrderNumber = "YE" + OrderHelper.GenerateOrderNumber();
            }

            ResultWeinXinTradeModel Rmodel = new ResultWeinXinTradeModel();
            //参数不能为空
            if (para == null)
            {
                return new ResultModel { IsSuccess = false, MsgCode = ResPrompt.ParaModelNotExist, Message = ResPrompt.ParaModelNotExistMessage };
            }
            if (para.total_fee == 0 || para.total_fee == null)
            {
               // LogService.InsertDBPay(para.UserInfoGuid, 1, 3, para.total_fee.ToString(), "金额不能为空值或者为0元！");
                return new ResultModel { IsSuccess = false, MsgCode = "0", Message = "金额不能为空值或者为0元！" };
            }
 
            try
            {
 
                //调用统一下单，获得下单结果
                WxPayData Result = UnifiedOrder(para,OrderNumber);

                Return_code = Result.GetValue("return_code").ToString();
                //请求微信接口返回结果集解析XML
                if (Result.GetValue("return_code").ToString() == "SUCCESS") //返回成功
                {
                    Rmodel.appid = Result.GetValue("appid").ToString();
                    Rmodel.mch_id = Result.GetValue("mch_id").ToString();
                    Rmodel.package = "Sign=WXPay";

                    //当return_code和result_code都为SUCCESS时，会返回：交易类型trade_type和预支付交易会话标识prepay_id
                    if (Result.GetValue("return_code").ToString() == "SUCCESS" && Result.GetValue("result_code").ToString() == "SUCCESS")
                    {
                        //微信生成的预支付回话标识，用于后续接口调用中使用，该值有效期为2小时
                        Rmodel.prepay_id = Result.GetValue("prepay_id").ToString(); //预支付交易会话标识prepay_id
                        //Rmodel.trade_type = Result.GetValue("trade_type").ToString(); //交易类型
                        
                    }
                    else
                    {
                        LogService.InsertDBPay(para.UserInfoGuid, 1, 3, para.total_fee.ToString(), "获取预支付交易会话标识prepay_id失败");
                        return new ResultModel { IsSuccess = false, MsgCode = "1012", Message = "获取预支付交易会话标识prepay_id失败" };
                    }
                    //Rmodel.nonce_str = Result.GetValue("nonce_str").ToString();
                    Rmodel.nonce_str = WxPayApi.GenerateNonceStr();
                    Rmodel.timestamp = GetTimeStamp(DateTime.Now).ToString(); //把当前时间转换成10位的时间戳

                    //从微信返回后在次签名返回给APP端
                    WxPayData pay_sign = new WxPayData();
                    pay_sign.SetValue("appid", Rmodel.appid);       //公众账号ID
                    pay_sign.SetValue("partnerid", Rmodel.mch_id);       //商户号
                    pay_sign.SetValue("noncestr", Rmodel.nonce_str);  //随机字符串
                    pay_sign.SetValue("package", "Sign=WXPay");                  
                    pay_sign.SetValue("prepayid", Rmodel.prepay_id);     //随机字符串
                    pay_sign.SetValue("timestamp", Rmodel.timestamp);     //时间戳

                    Rmodel.sign = pay_sign.MakeSign();     //签名

                    //Rmodel.sign ="";
                    //Rmodel.nonce_str = "";
                    //Rmodel.timestamp = ""; //把当前时间转换成10位的时间戳


                    #region 处理平台账户数据

                    try
                    {
                        #region 生成订单信息：分别为用户充值钱包余额和充值押金

                        decimal amount = decimal.Parse(para.total_fee.ToString())/100;

                        if (para.TypeName == 1) //表示押金充值业务处理
                        {
                            using (var db = new MintBicycleDataContext())
                            {
                                #region 押金充值基本信息表和添加押金充值记录表(订单表)
                                //查询
                                    //判断用户是否已充值押金
                                    var queryD = db.Deposit.FirstOrDefault(x => x.UserInfoGuid == para.UserInfoGuid && (x.Amount != 0 || x.Amount == decimal.Parse(YjAmoiunt)));
                                    if (queryD != null) //表示已充值押金
                                    {
                                    //LogService.InsertDBPay(para.UserInfoGuid, 1, 1, para.total_fee.ToString(), "用户已经充值押金不能重复充值！");
                                    return new ResultModel { IsSuccess = false, MsgCode = ResPrompt.AlipayExistErrorCode, Message = ResPrompt.AlipayExistErrorMessageMessage };
                                    }
                                try
                                {
                                    var query = db.Deposit.FirstOrDefault(s => s.UserInfoGuid == para.UserInfoGuid);
                                    if (query == null)
                                    {
                                        var Deposit = new Deposit();
                                        Deposit.DepositGuid = Guid.NewGuid();
                                        Deposit.Amount = 0;
                                        Deposit.UserInfoGuid = para.UserInfoGuid;
                                        Deposit.CreateBy = para.UserInfoGuid;
                                        Deposit.CreateTime = DateTime.Now;
                                        Deposit.IsDeleted = false;
                                        db.Deposit.InsertOnSubmit(Deposit);
                                        db.SubmitChanges();
                                    }
                                    else if (query != null && ((query.Amount == 0))) //修改
                                    {
                                        query.Amount = 0;
                                        query.IsDeleted = false;
                                        query.UpdateBy = para.UserInfoGuid;
                                        query.UpdateTime = DateTime.Now;
                                        db.SubmitChanges();
                                    }
                                    else //此用户已充值了押金不能重复充值
                                    {
                                        //FileLog.Log("用户充值押金异常信息：当前用户Guid为" + para.UserInfoGuid + "", typeName);
                                        LogHelper.Error("用户充值押金异常信息：当前用户Guid为" + para.UserInfoGuid + "");
                                        return new ResultModel { IsSuccess = false, MsgCode = ResPrompt.AlipayExistErrorCode, Message = ResPrompt.AlipayExistErrorMessageMessage };
                                    }

                                    //充值押金记录信息
                                    var UserDeposit = new UserDepositRechargeRecord();
                                    UserDeposit.UserDepositRechargeGuid = Guid.NewGuid();
                                    UserDeposit.UserInfoGuid = para.UserInfoGuid;
                                    UserDeposit.Amount = amount;
                                    UserDeposit.RechargeType = "微信";
                                    UserDeposit.MoneyType = "1";                        //1表示充值
                                    UserDeposit.Status = 2;                             //2交易创建，等待买家付款
                                    UserDeposit.PayDate = DateTime.Now;
                                    UserDeposit.OutTradeNo = OrderNumber;              //订单号码
                                    UserDeposit.Trade_no = null;                       //微信支付订单号
                                    UserDeposit.Sign_type = null;                     // 签名类型
                                    UserDeposit.Sign = null;                          // 签名
                                    UserDeposit.Bank_type = null;
                                    UserDeposit.BankName = null;
                                    UserDeposit.Openid = null;
                                    UserDeposit.Nonce_str = null;
                                    UserDeposit.Remark = " 用户Guid为" + para.UserInfoGuid + ",充值押金为：" + amount + "元。";
                                    UserDeposit.CreateBy = para.UserInfoGuid;
                                    UserDeposit.CreateTime = DateTime.Now;
                                    UserDeposit.IsDeleted = false;

                                    db.UserDepositRechargeRecord.InsertOnSubmit(UserDeposit);
                                    db.SubmitChanges();
                                }
                                catch (Exception ex)
                                {
                                    LogService.InsertDBPay(para.UserInfoGuid, 1, 1, para.total_fee.ToString(), "用户充值押金异常信息！");
                                    //FileLog.Log("用户充值押金异常信息：当前用户Guid为" + para.UserInfoGuid + ",生成押金充值订单信息异常!", typeName);
                                    LogHelper.Error("用户充值押金异常信息：当前用户Guid为" + para.UserInfoGuid + ",生成押金充值订单信息异常!",ex);
                                    return new ResultModel { IsSuccess = false, MsgCode = ResPrompt.AlipayDepositOrderErrorCode, Message = ResPrompt.AlipayDepositOrderErrorMessageMessage };
                                }

                                #endregion 押金充值基本信息表和添加押金充值记录表(订单表)
                            }
                        }
                        else //表示钱包余额业务处理
                        {
                            using (var db = new MintBicycleDataContext())
                            {
                                #region 充值账户信息表和添加用户充值余额记录表(订单表)

                                try
                                {
                                    var query = db.AccountInfo.FirstOrDefault(s => s.UserInfoGuid == para.UserInfoGuid);
                                    if (query == null)
                                    {
                                        var Account = new AccountInfo();
                                        Account.AccountGuid = Guid.NewGuid();
                                        Account.UserInfoGuid = para.UserInfoGuid;
                                        Account.BalanceAmount = 0;
                                        Account.UsableAmount = 0;
                                        Account.CreateTime = DateTime.Now;
                                        Account.CreateBy = para.UserInfoGuid;
                                        Account.IsDeleted = false;
                                        db.AccountInfo.InsertOnSubmit(Account);
                                        db.SubmitChanges();
                                    }

                                    //充值钱包金额记录表
                                    var UserRechargeRecord = new UserRechargeRecord();
                                    UserRechargeRecord.UserRechargeGuid = Guid.NewGuid();
                                    UserRechargeRecord.UserInfoGuid = para.UserInfoGuid;
                                    UserRechargeRecord.Amount = amount;
                                    //充值的方式：1支付宝；2微信
                                    UserRechargeRecord.RechargeType = "微信";
                                    //充值的状态：0充值失败；1充值成功
                                    UserRechargeRecord.Status = 2;                        //2交易创建，等待买家付款
                                    UserRechargeRecord.PayDate = DateTime.Now;
                                    UserRechargeRecord.OutTradeNo = OrderNumber;           //商户订单号
                                    UserRechargeRecord.Trade_no = null;                   //微信支付订单号
                                    UserRechargeRecord.Sign_type = null;                 // 签名类型
                                    UserRechargeRecord.Sign = null;                      // 签名
                                    UserRechargeRecord.Bank_type = null;
                                    UserRechargeRecord.BankName = null;
                                    UserRechargeRecord.Openid = null;
                                    UserRechargeRecord.Nonce_str = null;
                                    UserRechargeRecord.Remark = " 用户Guid为" + para.UserInfoGuid + ",充值钱包余额为：" + amount + "元。";
                                    UserRechargeRecord.CreateBy = para.UserInfoGuid;
                                    UserRechargeRecord.CreateTime = DateTime.Now;
                                    UserRechargeRecord.IsDeleted = false;

                                    db.UserRechargeRecord.InsertOnSubmit(UserRechargeRecord);
                                    db.SubmitChanges();
                                }
                                catch (Exception ex)
                                {
                                    LogService.InsertDBPay(para.UserInfoGuid, 1, 2, para.total_fee.ToString(), "用户充值余额异常信息！");
                                    //FileLog.Log("用户充值余额异常信息：当前用户Guid为" + para.UserInfoGuid + ",生成账户余额充值订单信息异常!", typeName);
                                    LogHelper.Error("用户充值余额异常信息：当前用户Guid为" + para.UserInfoGuid + ",生成账户余额充值订单信息异常!", ex);
                                    return new ResultModel { IsSuccess = false, MsgCode = ResPrompt.AlipayAccountOrderErrorCode, Message = ResPrompt.AlipayAccountOrdeErrorMessageMessage };
                                }

                                #endregion 充值账户信息表和添加用户充值余额记录表(订单表)
                            }
                        }

                        #endregion 生成订单信息：分别为用户充值钱包余额和充值押金
                    }
                    catch (Exception ex)
                    {
                        LogService.InsertDBPay(para.UserInfoGuid, 1, 3, para.total_fee.ToString(), "用户充值押金异常信息！");
                        //FileLog.Log("用户微信充值异常：当前用户Guid为" + para.UserInfoGuid + ",服务器生成预支付交易单信息异常!", typeName);
                        LogHelper.Error("用户微信充值异常：当前用户Guid为" + para.UserInfoGuid + ",服务器生成预支付交易单信息异常!", ex);
                        return new ResultModel { IsSuccess = false, MsgCode = ResPrompt.AlipayServiceErrorCode, Message = ResPrompt.AlipayServiceErrorMessageMessage };
                    }

                    #endregion 处理平台账户数据

                    result.Message = "生成预支付交易单成功";
                    result.ResObject = Rmodel;
                }
                else if (Result.GetValue("return_code").ToString() == "FAIL")   //失败
                {
                    err_code = Result.GetValue("err_code").ToString();
                    //错误码返回
                    strCode = GetErrCodeStr(err_code);
                    if (!string.IsNullOrEmpty(strCode))
                    {
                        LogService.InsertDBPay(para.UserInfoGuid, 1, 3, para.total_fee.ToString(), "生成预付单请求失败！");
                        return new ResultModel { IsSuccess = false, MsgCode = "1010", Message = "生成预付单请求失败" };
                    }
                    //FileLog.Log("生成预付单请求失败：错误信息：" + strCode + ",返回的结果集是" + Result + ",服务器生成订单信息异常!", "WeiXin_Exption_radeLog");
                    LogHelper.Error("生成预付单请求失败:错误信息：" + strCode+ "返回的结果集是：" + Result);
                }
            }
            catch (Exception ex)
            {
                LogService.InsertDBPay(para.UserInfoGuid, 1, 3, para.total_fee.ToString(), "生成预付单请求失败！");
                //FileLog.Log("生成预付单请求失败：return_code" + Return_code + ",strCode!", "WeiXinError_TradeLog");
                LogHelper.Error("生成预付单请求异常:" + ex.Message + "return_code：" + Return_code, ex);
                return new ResultModel { IsSuccess = false, MsgCode = "1011", Message = "生成预付单请求异常" };
            }

            return result;
        }

        /**
         * 调用统一下单，获得下单结果
         * @return 统一下单结果
         * @失败时抛异常WxPayException
         */

        //public WxPayData GetUnifiedOrderResult(WeixinAlipayTradeModel Model, string OrderNumber)
        //{
        //    //统一下单
        //    WxPayData data = new WxPayData();
        //    data.SetValue("body", Model.body);
        //    data.SetValue("out_trade_no", OrderNumber);         //生成订单号
        //    data.SetValue("total_fee", Model.total_fee);        //订单总金额
        //    //data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss")); //交易起始时间
        //    //data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss")); //交易结束时间
        //    data.SetValue("trade_type", "APP");       //支付类型



        //    //*@param WxPaydata inputObj 提交给统一下单API的参数
        //    WxPayData result = UnifiedOrder(data);

        //    //prepay_id--预支付交易会话标识
        //    if (!result.IsSet("appid") || !result.IsSet("prepay_id") || result.GetValue("prepay_id").ToString() == "")
        //    {
        //        //Log.Error(this.GetType().ToString(), "调用统一下单异常!");
        //        FileLog.Log("调用统一下单错误：prepay_id是：" + result.GetValue("prepay_id").ToString() + "", "WeiXinError_TradeLog");
        //        //throw new WxPayException("UnifiedOrder response error!");
        //    }
        //    unifiedOrderResult = result;
        //    return result;
        //}

        /**
      * 统一下单
      * @param WxPaydata inputObj 提交给统一下单API的参数
      * @param int timeOut 超时时间
      * @throws WxPayException
      * @return 成功时返回，其他抛异常
      **/
        public  WxPayData UnifiedOrder(WeixinAlipayTradeModel Model, string OrderNumber, int timeOut = 6)
        {
            string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            //检测必填参数
            if (string.IsNullOrEmpty(OrderNumber))
            {
                throw new WxPayException("缺少统一支付接口必填参数OrderNumber！");
            }
            else if (string.IsNullOrEmpty(Model.body))
            {
                throw new WxPayException("缺少统一支付接口必填参数body！");
            }
            else if (Model.total_fee==0 || Model.total_fee==null)
            {
                throw new WxPayException("缺少统一支付接口必填参数total_fee！");
            }

            WxPayData data = new WxPayData();
            data.SetValue("body", Model.body);
            data.SetValue("out_trade_no", OrderNumber);         //生成订单号
            data.SetValue("total_fee", Model.total_fee);        //订单总金额
            data.SetValue("trade_type", "APP");                 //支付类型
           

            //异步通知url未设置，则使用配置文件中的url
            if (!data.IsSet("notify_url"))
            {
                data.SetValue("notify_url", W_notify_url);//异步通知url
            }
            data.SetValue("appid", WxPayConfig.APPID);                   //公众账号ID
            data.SetValue("mch_id", WxPayConfig.MCHID);                  //商户号
            data.SetValue("spbill_create_ip", String_IP);          //终端ip
            data.SetValue("nonce_str", WxPayApi.GenerateNonceStr());     //随机字符串
            data.SetValue("sign", data.MakeSign());                     //签名
            
            string xml = data.ToXml();

            //FileLog.Log("日期：" + DateTime.Now + ", UnifiedOrder方法请求返回的Xml: " + xml + "", "WeiXinRequestxml");
            string response = HttpService.Post(xml, url, false, timeOut);  //调用HTTP通信接口以提交数据到API
            //FileLog.Log("日期：" + DateTime.Now + ", UnifiedOrder方法请求返回的Xml: " + response + "", "WeiXinResponsexml");
            WxPayData result = new WxPayData();
            result.FromXml(response);

            //prepay_id--预支付交易会话标识
            if (!result.IsSet("appid") || !result.IsSet("prepay_id") || result.GetValue("prepay_id").ToString() == "")
            {
                //Log.Error(this.GetType().ToString(), "调用统一下单异常!");
                //FileLog.Log("调用统一下单错误：prepay_id是：" + result.GetValue("prepay_id").ToString() + "", "WeiXinError_TradeLog");
                LogHelper.Error("调用统一下单错误,prepay_id是：" + result.GetValue("prepay_id").ToString());
                //throw new WxPayException("UnifiedOrder response error!");
            }
            unifiedOrderResult = result;


            //WxPayData data = new WxPayData();
            return result;
        }

        /// <summary>
        /// 错误状态码处理
        /// </summary>
        /// <param name="st"></param>
        /// <returns></returns>
        public static string GetErrCodeStr(string err_code)
        {
            //状态
            var str = string.Empty;
            switch (err_code)
            {
                case "NOAUTH":
                    str = "商户未开通此接口权限";
                    break;

                case "NOTENOUGH":
                    str = "用户帐号余额不足";
                    break;

                case "ORDERPAID":
                    str = "商户订单已支付，无需重复操作";
                    break;

                case "ORDERCLOSED":
                    str = "当前订单已关闭，无法支付";
                    break;

                case "SYSTEMERROR":
                    str = "系统超时";
                    break;

                case "APPID_NOT_EXIST":
                    str = "参数中缺少APPID";
                    break;

                case "MCHID_NOT_EXIST":
                    str = "参数中缺少MCHID";
                    break;

                case "APPID_MCHID_NOT_MATCH":
                    str = "appid和mch_id不匹配";
                    break;

                case "LACK_PARAMS":
                    str = "缺少必要的请求参数";
                    break;

                case "OUT_TRADE_NO_USED":
                    str = "同一笔交易不能多次提交";
                    break;

                case "SIGNERROR":
                    str = "参数签名结果不正确";
                    break;

                case "XML_FORMAT_ERROR":
                    str = "XML格式错误";
                    break;

                case "REQUIRE_POST_METHOD":
                    str = "未使用post传递参数 ";
                    break;

                case "NOT_UTF8":
                    str = "未使用指定编码格式 ";
                    break;

                default:
                    str = "未知状态";
                    break;
            }
            return str;
        }

        /// <summary>
        /// 统一下单接口返回结果
        /// </summary>
        public WxPayData unifiedOrderResult { get; set; }

        /// <summary>
        /// 获取时间戳Timestamp
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public int GetTimeStamp(DateTime dt)
        {
            DateTime dateStart = new DateTime(1970, 1, 1, 8, 0, 0);
            int timeStamp = Convert.ToInt32((dt - dateStart).TotalSeconds);
            return timeStamp;
        }

        #endregion

        #region 微信支付结果通用通知

        public void ProcessNotify()
        {
            WxPayData notifyData = GetNotifyData();

            #region
            // 注意：同样的通知可能会多次发送给商户系统。商户系统必须能够正确处理重复的通知。 
            //当收到通知进行处理时，首先检查对应业务数据的状态，判断该通知是否已经处理过，如果没有处理过再进行处理，如果处理过直接返回结果成功。
            //查询

            #endregion



            #region 检查支付结果中transaction_id是否存在
            if (!notifyData.IsSet("transaction_id"))
            {
                //若transaction_id不存在，则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "支付结果中微信订单号不存在");

                FileLog.Log("支付结果中微信订单号不存在,时间：" + DateTime.Now + ",错误信息：" + res.ToXml(), "WeiXinSignErrorLog");
                //Log.Error(this.GetType().ToString(), "The Pay result is error : " + res.ToXml());
                System.Web.HttpContext.Current.Response.Write(res.ToXml());
                System.Web.HttpContext.Current.Response.End();
            }
            #endregion

            //获取微信支付订单号
            string transaction_id = notifyData.GetValue("transaction_id").ToString();
            //FileLog.Log("交易订单号：" + transaction_id + "\r\n", "RefundLog");

            //查询订单，判断订单真实性
            if (!QueryOrder(transaction_id))
            {
                //若订单查询失败，则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "订单查询失败");

                LogHelper.Error("订单查询失败, 时间：" + DateTime.Now + ", 错误信息：" + res.ToXml());
                //FileLog.Log("订单查询失败,时间：" + DateTime.Now + ",错误信息：" + res.ToXml(), "WeiXinSignErrorLog");
                System.Web.HttpContext.Current.Response.Write(res.ToXml());
                System.Web.HttpContext.Current.Response.End();
            }
            //查询订单成功
            else
            {
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "SUCCESS");
                res.SetValue("return_msg", "OK");
                LogHelper.Error("微信异步通知支付结果成功, 时间：" + DateTime.Now+", 交易订单号："+ transaction_id + "");
                //Log.Info(this.GetType().ToString(), "order query success : " + res.ToXml());

                System.Web.HttpContext.Current.Response.Write(res.ToXml());
                System.Web.HttpContext.Current.Response.End();
            }


        }

        //查询订单返回结果集,并处理修改平台的订单状态
        private bool QueryOrder(string transaction_id)
        {
            var result = new ResultModel();
            decimal Amount = 0;
            string TradeStatus = string.Empty;

            WxPayData req = new WxPayData();
            req.SetValue("transaction_id", transaction_id); 
            WxPayData res = OrderQuery(req);

            //修改平台对应的数据信息
            if (res.GetValue("return_code").ToString() == "SUCCESS" &&
                res.GetValue("result_code").ToString() == "SUCCESS")
            {
                //FileLog.Log("查询订单返回结果集,时间：" + DateTime.Now + ",返回状态：" + res.GetValue("return_code").ToString() + "，" + res.GetValue("result_code").ToString(), "WeiXinSignSuccessLog");

                    NotifyWeinXinResultModel notityModel = new NotifyWeinXinResultModel();
                        //return_code为SUCCESS的时候有返回
                        notityModel.appid = res.GetValue("appid").ToString();              //应用ID
                        notityModel.mch_id = res.GetValue("mch_id").ToString();           //商户号
                        notityModel.nonce_str = res.GetValue("nonce_str").ToString();    //随机字符串
                        notityModel.sign = res.GetValue("sign").ToString();              //签名

                        notityModel.openid = res.GetValue("openid").ToString();          //用户在商户appid下的唯一标识
                        notityModel.trade_type = res.GetValue("trade_type").ToString();  //交易类型
                        notityModel.bank_type = res.GetValue("bank_type").ToString();    //付款银行
                        notityModel.total_fee = int.Parse(res.GetValue("total_fee").ToString());    //总金额
                        notityModel.cash_fee = int.Parse(res.GetValue("cash_fee").ToString());     //现金支付金额
                        notityModel.transaction_id = res.GetValue("transaction_id").ToString();    //微信支付订单号
                        notityModel.out_trade_no = res.GetValue("out_trade_no").ToString();       //商户订单号
                        notityModel.time_end = res.GetValue("time_end").ToString();               //支付完成时间
                       // notityModel.trade_state_desc = res.GetValue("trade_state_desc").ToString();      //交易状态描述 
                        notityModel.trade_state = res.GetValue("trade_state").ToString();               //交易状态
                                                                         
                        Amount = decimal.Parse(notityModel.total_fee.ToString()) / 100; //金额

                    //FileLog.Log("0000000\r\n"+ Amount, "WeiXinExceptionLog0000000");
                    //notityModel.total_fee = Amount;
                    //FileLog.Log("22222222\r\n" + notityModel.total_fee, "WeiXinExceptionLog222222222222");
                    #region 处理订单业务逻辑
                    //FileLog.Log("查询订单返回结果集:"+ res.ToXml()+"\r\n", "WeiXinExceptionLog");

                try
                {
                    //修改平台订单状态                                                                                               
                    if (!string.IsNullOrEmpty(notityModel.out_trade_no)  && notityModel.trade_state == "SUCCESS" && notityModel.out_trade_no.Contains("YJ")) //押金业务
                    {
                        //FileLog.Log("1\r\n", "WeiXinExceptionLog");

                        #region 校验通知数据的正确性
                        result = _UserAccountService.WeixinGetUserDepositByout_trade_no(notityModel.out_trade_no, notityModel.total_fee.ToString());
                        //FileLog.Log("2\r\n", "WeiXinExceptionLog");

                        if (!result.IsSuccess)
                        {
                            WxPayData results = new WxPayData();
                            results.SetValue("return_code", "FAIL");
                            results.SetValue("return_msg", "金额不匹配或者商户订单号不存在");
                            System.Web.HttpContext.Current.Response.Write(results.ToXml());
                            System.Web.HttpContext.Current.Response.End();
                            //FileLog.Log("3\r\n", "WeiXinExceptionLog");
                            LogHelper.Error("金额不匹配或者商户订单号不存在, 时间：" + DateTime.Now + ", 押金金额：" + notityModel.total_fee.ToString() + "");
                        }
                        else if (result.IsSuccess && result.MsgCode == "1")
                        {
                            //FileLog.Log("4\r\n", "WeiXinExceptionLog");
                            WxPayData results = new WxPayData();
                            results.SetValue("return_code", "SUCCESS");
                            results.SetValue("return_msg", "已修改订单状态成功，无须再做修改操作");
                            System.Web.HttpContext.Current.Response.Write(results.ToXml());
                            System.Web.HttpContext.Current.Response.End();
                            //FileLog.Log("5\r\n", "WeiXinExceptionLog");
                            LogHelper.Error("已修改订单状态成功，无须再做修改操作, 时间：" + DateTime.Now);
                        }
                        else
                        {
                            //FileLog.Log("6\r\n", "WeiXinExceptionLog");
                            notityModel.Status = 1; //充值成功
                            //修改押金充值的状态为成功
                            bool flag = _UserAccountService.UserReOrUpdateDepositToWeiXinPay(notityModel);
                            //FileLog.Log("7\r\n", "WeiXinExceptionLog");
                            if (!flag)
                            {
                                //notityModel.Status = 0; //充值失败
                                //bool flag1 = _UserAccountService.UserReOrUpdateDepositToWeiXinPay(notityModel);
                                //FileLog.Log("9\r\n", "WeiXinExceptionLog");
                                //日志
                                //FileLog.Log("修改充值押金记录数据失败，交易订单号：" + notityModel.out_trade_no + ",时间：" + DateTime.Now + ",返回状态：" + res.GetValue("return_code").ToString() + "，" + res.GetValue("result_code").ToString(), "WeiXinRechargeYaJin_FailLog");
                                WxPayData results = new WxPayData();
                                results.SetValue("return_code", "FAIL");
                                results.SetValue("return_msg", "修改充值押金记录数据失败");
                                System.Web.HttpContext.Current.Response.Write(results.ToXml());
                                System.Web.HttpContext.Current.Response.End();
                                //FileLog.Log("10\r\n", "WeiXinExceptionLog");
                                LogHelper.Error("修改充值押金记录数据失败, 时间：" + DateTime.Now+"充值的状态:"+ flag);
                            }
                            //发送短信消息通知用户
                            Guid userGuid = new Guid();
                            string T = "押金";
                            //FileLog.Log("11\r\n", "WeiXinExceptionLog");
                            string remark = "【薄荷单车】您账户" + DateTime.Now.Month + "月" + DateTime.Now.Day + "日" + "收到押金充值\"" + Amount + "\"元,请及时查看。";
                            bool flg = _UserAccountService.UsersSendSMS(userGuid, notityModel.out_trade_no, T, remark);
                           // FileLog.Log("12\r\n", "WeiXinExceptionLog");
                        }

                        #endregion 校验通知数据的正确性

                    }
                    else  //余额
                    {
                        #region 校验通知数据的正确性
                        result = _UserRechargeService.WeixinGetUserRechargeRecordByout_trade_no(notityModel.out_trade_no, notityModel.total_fee.ToString());
                        if (!result.IsSuccess)
                        {
                            WxPayData results = new WxPayData();
                            results.SetValue("return_code", "FAIL");
                            results.SetValue("return_msg", "金额不匹配或者商户订单号不存在");
                            System.Web.HttpContext.Current.Response.Write(results.ToXml());
                            System.Web.HttpContext.Current.Response.End();
                            LogHelper.Error("金额不匹配或者商户订单号不存在, 时间：" + DateTime.Now + ", 押金金额：" + notityModel.total_fee.ToString() + "");
                        }
                        else if (result.IsSuccess && result.MsgCode == "1")
                        {
                            WxPayData results = new WxPayData();
                            results.SetValue("return_code", "SUCCESS");
                            results.SetValue("return_msg", "已修改订单状态成功，无须再做修改操作");
                            System.Web.HttpContext.Current.Response.Write(results.ToXml());
                            System.Web.HttpContext.Current.Response.End();

                            LogHelper.Error("已修改订单状态成功，无须再做修改操作, 时间：" + DateTime.Now);
                        }
                        else
                        {
                            notityModel.Status = 1; //充值成功
                            bool flag = _UserRechargeService.UserRechargeOrAccountInfoWeiXinPay(notityModel);
                            
                            if (!flag)
                            {
                                //日志
                                FileLog.Log("修改充值余额记录数据失败，交易订单号：" + notityModel.out_trade_no + ",时间：" + DateTime.Now + ",返回状态：" + res.GetValue("return_code").ToString() + "，" + res.GetValue("result_code").ToString(), "WeiXinRechargeYue_FailLog");
                                WxPayData results = new WxPayData();
                                results.SetValue("return_code", "FAIL");
                                results.SetValue("return_msg", "修改充值余额记录数据失败");
                                System.Web.HttpContext.Current.Response.Write(results.ToXml());
                                System.Web.HttpContext.Current.Response.End();
                                LogHelper.Error("修改充值押金记录数据失败, 时间：" + DateTime.Now + "充值的状态:" + flag);

                            }
                            //发送短信消息通知用户
                            Guid userGuid = new Guid();
                            string T = "余额";

                            string remark = "【薄荷单车】您账户" + DateTime.Now.Month + "月" + DateTime.Now.Day + "日" + "收到余额充值\"" + Amount + "\"元,请及时查看。";
                            bool flg = _UserAccountService.UsersSendSMS(userGuid, notityModel.out_trade_no, T, remark);
                        }

                        #endregion 校验通知数据的正确性
                    }

                    #endregion
                }
                catch (Exception ex)
                {
                    //WxPayData rese = new WxPayData();
                    //rese.SetValue("return_code", "FAIL");
                    //rese.SetValue("return_msg", "微信支付结果通知异常");
                    //FileLog.Log(ex.Source + "\r\n" + ex.Data.ToString(), "WeiXinExceptionLog");
                    LogHelper.Error(ex.Source + "\r\n" + ex.Data.ToString(),ex);
                    // FileLog.Log("微信支付结果通知异常,时间：" + DateTime.Now + ",异常Message:" + ex.Message + ",返回状态：" + res.GetValue("return_code").ToString() + "，" + res.GetValue("result_code").ToString(), "WeiXinExceptionLog");
                    //Log.Info(this.GetType().ToString(), "order query success : " + res.ToXml());

                    //System.Web.HttpContext.Current.Response.Write(res.ToXml());
                    //System.Web.HttpContext.Current.Response.End();
                }
                return true;
            }
            else  //充值失败
            {
                //FileLog.Log("充值失败,时间：" + DateTime.Now + ",返回状态：" + res.GetValue("return_code").ToString() + "，" + res.GetValue("result_code").ToString(), "WeiXinRecharge_FailLog");
                LogHelper.Error("充值失败,时间：" + DateTime.Now + ",返回状态：" + res.GetValue("return_code").ToString() + "，" + res.GetValue("result_code").ToString());
                return false;
            }
        }


        /// <summary>
        /// 接收从微信支付后台发送过来的数据并验证签名
        /// </summary>
        /// <returns>微信支付后台返回的数据</returns>
        public WxPayData GetNotifyData()
        {
            //接收从微信后台POST过来的数据
            System.IO.Stream s = System.Web.HttpContext.Current.Request.InputStream;
            int count = 0;
            byte[] buffer = new byte[1024];
            StringBuilder builder = new StringBuilder();
            while ((count = s.Read(buffer, 0, 1024)) > 0)
            {
                builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
            }
            s.Flush();
            s.Close();
            s.Dispose();

           // FileLog.Log("接收来自微信的数据:" + builder.ToString() + ",时间：" + DateTime.Now, "WeiXinSignSuccessLog");

            //Log.Info(this.GetType().ToString(), "Receive data from WeChat : " + builder.ToString());

            //转换数据格式并验证签名
            WxPayData data = new WxPayData();
            try
            {
                data.FromXml(builder.ToString());
            }
            catch (WxPayException ex)
            {
                //若签名错误，则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", ex.Message);

                LogHelper.Error("微信签名错,时间：" + DateTime.Now + ",错误信息：" + ex.Message,ex);
                //FileLog.Log("微信签名错,时间：" + DateTime.Now + ",错误信息：" + ex.Message, "WeiXinSignErrorLog");
                //Log.Error(this.GetType().ToString(), "Sign check error : " + res.ToXml());

                System.Web.HttpContext.Current.Response.Write(res.ToXml());
                System.Web.HttpContext.Current.Response.End();
            }
            //FileLog.Log("微信签名成功,时间：" + DateTime.Now + ",返回的信息：" + data, "WeiXinSignSuccessLog");
 
            return data;
        }

        /**
* 传5个参数必填
* 查询订单
* @param WxPayData inputObj 提交给查询订单API的参数
* @param int timeOut 超时时间
* @throws WxPayException
* @return 成功时返回订单查询结果，其他抛异常
*/
        public static WxPayData OrderQuery(WxPayData inputObj, int timeOut = 30)
        {
            string url = "https://api.mch.weixin.qq.com/pay/orderquery";
            //检测必填参数
            if (!inputObj.IsSet("transaction_id"))
            {
                throw new WxPayException("订单查询接口中，transaction_id至少填一个！");
            }

            WxPayData result = new WxPayData();
            try
            {
                inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID
                inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号
                inputObj.SetValue("nonce_str", WxPayApi.GenerateNonceStr());//随机字符串
                inputObj.SetValue("sign", inputObj.MakeSign());//签名

            string xml = inputObj.ToXml();
            string response = HttpService.Post(xml, url, false, timeOut);//调用HTTP通信接口提交数据

 
            //将xml格式的数据转化为对象以返回
          
            result.FromXml(response);

            //FileLog.Log("查询订单,时间：" + DateTime.Now + ",inputObj:"+inputObj+",返回的信息XML：" + xml+ "response:"+ response, "WeiXinExceptionLog");

            }
            catch (Exception ex)
            {
                LogHelper.Error("查询订单异常,时间：" + DateTime.Now, ex);
                //FileLog.Log("查询订单异常,时间：" + DateTime.Now, "WeiXinExceptionLog");
            }
         
            return result;
        }

        /// <summary>
        /// 交易状态说明
        /// </summary>
        /// <param name="T"></param>
        /// <returns></returns>
        public static string GetTradeStatus(string T)
        {
            //充值的状态：SUCCESS—支付成功;REFUND—转入退款；NOTPAY—未支付;CLOSED—已关闭;REVOKED—已撤销（刷卡支付;USERPAYING--用户支付中;PAYERROR--支付失败(其他原因，如银行返回失败)
            string str = string.Empty;
            switch (T)
            {
                case "SUCCESS":
                    str = "支付成功";
                    break;

                case "REFUND":
                    str = "转入退款";
                    break;

                case "NOTPAY":
                    str = "未支付";
                    break;

                case "CLOSED":
                    str = "已关闭";
                    break;
                case "REVOKED":
                    str = "已撤销";
                    break;

                case "USERPAYING":
                    str = "用户支付中";
                    break;

                case "PAYERROR":
                    str = "支付失败";
                    break;


                default:
                    str = "未知错误";
                    break;
            }
            return str;
        }

        /// <summary>
        /// 查询是否修改押金订单状态成功
        /// </summary>
        /// <param name="para">充值的类别1：支付宝充值押金；2：微信充值押金</param>
        /// <returns></returns>
        public ResultModel GetRechargeStatusByUserInfoGuid(WeixinIsSuccessOrFail para)
        {
            string sqlStr = string.Empty;
            string RechargeType = string.Empty;
            var result = new ResultModel();
            if (para == null)
            {
                return new ResultModel { IsSuccess = false, MsgCode = ResPrompt.ParaModelNotExist, Message = ResPrompt.ParaModelNotExistMessage };
            }
            if (para.TypeName==1)
            {
                RechargeType = "支付宝";
            } else
            {
                RechargeType = "微信";
            }
            if (para.TypeName == 1) //支付宝充值押金
            {
                sqlStr = "select top 1 * from UserDepositRechargeRecord where  UserInfoGuid='" + para.UserInfoGuid + "' and  RechargeType='"+ RechargeType + "' and MoneyType=1  order by CreateTime desc ";
                DataSet ds = DbHelperSQL.Query(sqlStr);
                if (ds != null && ds.Tables[0].Rows.Count > 0 && ds.Tables[0].Rows[0]["Status"].ToString() == "1")
                {
                    result.IsSuccess = true;
                    result.Message = "押金充值成功";

                } else if (ds.Tables[0].Rows[0]["Status"].ToString() == "2")
                {
                    result.IsSuccess = false;
                    result.Message = "交易创建，等待买家付款";
                }
                else
                {
                    result.IsSuccess = false;
                    result.Message = "不存在押金充值记录信息";
                }
            }
            return result;
        }


        #endregion

        #region 微信退款申请

        /// <summary>
        /// 微信退款申请
        /// </summary>
        /// <param name="agrs">申请参数</param>
        /// <returns></returns>
        public ResultModel WeixinRefund(UserDepositRefundModel agrs)
        {
            ResultModel result = new ResultModel();

            if (agrs.UserInfoGuid == Guid.Empty || agrs.UserInfoGuid == null)
            {
                result.IsSuccess = false;
                result.MsgCode = "0";
                result.Message = "指定的用户GUID不能为空值";
               // FileLog.Log("4\r\n", "WeiXinRefundLog");
                return result;
            }

            using (var db = new MintBicycleDataContext())
            {
                IUserAccountService userService = new UserAccountService();
               // FileLog.Log("5\r\n", "WeiXinRefundLog");
                //判断用户信息
                var user = db.UserInfo.FirstOrDefault(q => q.UserInfoGuid == agrs.UserInfoGuid && (!q.IsDeleted));
                //FileLog.Log("6\r\n", "WeiXinRefundLog");
                if (null == user)
                {
                    LogService.InsertDBPay(agrs.UserInfoGuid, 1, 2,"押金", "用户不存在！");
                    result.IsSuccess = false;
                    result.MsgCode = "0";
                    result.Message = "用户不存在";
                    return result;
                }

                //用户押金记录
                var deposit = db.Deposit.FirstOrDefault(q => q.UserInfoGuid == agrs.UserInfoGuid && !q.IsDeleted);
                //FileLog.Log("7\r\n", "WeiXinRefundLog");
                if (null == deposit || deposit.Amount == 0)
                {
                    LogService.InsertDBPay(agrs.UserInfoGuid, 1, 2, deposit.Amount.ToString(), "用户未缴纳押金！");
                    result.IsSuccess = false;
                    result.MsgCode = "0";
                    result.Message = "用户未缴纳押金";
                   // FileLog.Log("77\r\n", "WeiXinRefundLog");
                    return result;
                }

                //查询押金记录-只查询微信
                var deposit_log = db.UserDepositRechargeRecord.OrderByDescending(q=>q.CreateTime).FirstOrDefault(q => !q.IsDeleted&& q.UserInfoGuid == agrs.UserInfoGuid && q.RechargeType == "微信" && q.MoneyType == "1" && q.Status==1);
                //FileLog.Log("8\r\n", "WeiXinRefundLog");
                if (null == deposit_log || deposit.Amount == 0)
                {
                    LogService.InsertDBPay(agrs.UserInfoGuid, 1, 2, deposit_log.Amount.ToString(), "用户未通过微信支付缴纳押金！");
                    result.IsSuccess = false;
                    result.MsgCode = "0";
                    result.Message = "用户未通过微信支付缴纳押金";
                    return result;
                }

                //检查押金与押金记录是否一致
                if (deposit.Amount != deposit_log.Amount)
                {
                    LogService.InsertDBPay(agrs.UserInfoGuid, 1, 2, deposit_log.Amount.ToString(), "用户押金与押金缴纳记录不符！");
                    result.IsSuccess = false;
                    result.MsgCode = "0";
                    result.Message = "用户押金与押金缴纳记录不符";
                    return result;
                }

                WxPayData refund = new WxPayData();
                refund.SetValue("appid", WxPayConfig.APPID);          //公众账号ID
                refund.SetValue("mch_id", WxPayConfig.MCHID);        //商户号               
                refund.SetValue("nonce_str", WxPayApi.GenerateNonceStr());     //随机字符串
                refund.SetValue("transaction_id", deposit_log.Trade_no); //微信订单号
                refund.SetValue("out_refund_no", deposit_log.OutTradeNo); //退款单号
                refund.SetValue("total_fee", (int)(deposit_log.Amount*100)); //退款单号
                refund.SetValue("refund_fee", (int)(deposit_log.Amount * 100)); //退款金额
                refund.SetValue("op_user_id", WxPayConfig.MCHID); //操作员

                refund.SetValue("sign", refund.MakeSign());        //签名

                //创建xml
                string xml = refund.ToXml();
               // FileLog.Log("日期：" + DateTime.Now + ",UnifiedOrder方法请求返回的Xml: " + xml + "", "WeiXinRefundLog");

                //发送退款请求并接收处理结果
                string refund_url = "https://api.mch.weixin.qq.com/secapi/pay/refund";              
                string response = HttpService.Post(xml, refund_url, true, 30);
                //FileLog.Log("9\r\n"+ response, "WeiXinRefundLog");

                WxPayData result_data = new WxPayData();
                result_data.FromXml(response);

                if (result_data.IsSet("return_code") && result_data.GetValue("return_code").ToString() == "SUCCESS" && result_data.IsSet("result_code") && result_data.GetValue("result_code").ToString() == "SUCCESS")
                {
                    deposit_log.IsDeleted = true;

                    deposit.Amount = 0;
                    deposit.UpdateBy = agrs.UserInfoGuid;
                    deposit.UpdateTime = DateTime.Now;

                    // db.SubmitChanges();

                    var UserDepositRecharge = new UserDepositRechargeRecord();
                    UserDepositRecharge.UserDepositRechargeGuid = Guid.NewGuid();
                    UserDepositRecharge.UserInfoGuid = agrs.UserInfoGuid;
                    UserDepositRecharge.Amount = deposit_log.Amount;
                    //退款的方式：1支付宝；2微信
                    UserDepositRecharge.RechargeType = "微信";
                    UserDepositRecharge.MoneyType = "2";   //MoneType=2表示退押金
                                                           //退款的状态：0退款失败；1退款成功
                    UserDepositRecharge.Status = 1;
                    UserDepositRecharge.PayDate = DateTime.Now;   //退款时间
                    UserDepositRecharge.OutTradeNo = deposit_log.OutTradeNo;                   //订单号码
                    UserDepositRecharge.Trade_no = deposit_log.Trade_no;                        //支付宝交易号
                    UserDepositRecharge.Sign_type = "MD5";                        // 签名类型RSA2
                    UserDepositRecharge.Sign = deposit_log.Sign;                              // 签名
                    UserDepositRecharge.Remark = " 用户Guid为" + agrs.UserInfoGuid + "退押金了99元。";
                    UserDepositRecharge.CreateBy = agrs.UserInfoGuid;
                    UserDepositRecharge.CreateTime = DateTime.Now;
                    UserDepositRecharge.IsDeleted = false;

                    db.UserDepositRechargeRecord.InsertOnSubmit(UserDepositRecharge);

                    try
                    {
                        db.SubmitChanges();
                    }
                    catch (Exception exc)
                    {
                        LogService.InsertDBPay(agrs.UserInfoGuid, 1, 2, deposit_log.Amount.ToString(), "退款出现错误，请联系客服！");
                        result.IsSuccess = false;
                        result.IsSuccess = false;
                        result.MsgCode = "0";
                        result.Message = "退款出现错误，请联系客服！";
                        //FileLog.Log("微信退押金：退款申请提交失败: " + exc.Message + "\r\n" + response, "WeiXinRefundLog");
                        LogHelper.Error("微信退押金,退款申请提交失败:" + exc.Message + "response" + response + "");
                    }

                    //发送短信消息通知用户
                    string T = string.Empty;
                    string OutTradeNo = string.Empty;

                    string remark = "【薄荷单车】您申请的退款[" + deposit_log.Amount + "]元,已处理成功,微信支付退款有一定延时,用零钱支付的退款20分钟内到账,银行卡支付的退款3个工作日。";
                    bool flg = userService.UsersSendSMS(agrs.UserInfoGuid, OutTradeNo, T, remark);

                    result.IsSuccess = true;
                    result.MsgCode = "0";
                    result.Message = "退款申请已提交成功";
                    //FileLog.Log("10退款申请已提交成功\r\n", "WeiXinRefundLog");
                 
                    return result;

                } else if (result_data.GetValue("result_code").ToString() == "FAIL" && result_data.GetValue("err_code").ToString() == "NOTENOUGH")
                {
                    LogService.InsertDBPay(agrs.UserInfoGuid, 1, 2, deposit_log.Amount.ToString(), "微信退押金失败：商户可用退款余额不足！");
                    //FileLog.Log("微信退押金失败：商户可用退款余额不足: " + result_data.GetValue("err_code").ToString() +"-"+result_data.GetValue("err_code").ToString() + "", "WeiXinRefundLog");
                    result.IsSuccess = false;
                    result.MsgCode = "0";
                    result.Message = "退款出现错误，请联系客服！";

                    LogHelper.Error("微信退押金失败,商户可用退款余额不足: " + result_data.GetValue("err_code").ToString() + " - " + result_data.GetValue("err_code").ToString() + "");
                    return result;
                
                }
                else
                {
                    LogService.InsertDBPay(agrs.UserInfoGuid, 1, 2, deposit_log.Amount.ToString(), "退款出现错误，请联系客服！");
                    //FileLog.Log("微信退押金：退款申请提交失败: " + response + "", "WeiXinRefundLog");
                    result.IsSuccess = false;
                    result.MsgCode = "0";
                    result.Message = "退款出现错误，请联系客服！";
                    LogHelper.Error("微信退押金,退款申请提交失败: :" + response + "用户Guid：" + agrs.UserInfoGuid);
                    return result;
                }
            }
        }

        #endregion

    }
}